<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="学校管理" name="school_list">
        <el-form :inline="true" @keyup.enter.native="searchSchool">

          <el-form-item>
            <el-select
              v-model="query.school_type"
              filterable
              clearable
              placeholder="请选择所属阶段">
              <el-option
                v-for="item in schoolTypeListForQuery"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-input placeholder="学校名称/校长/联系电话" v-model="query.keyWord" style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button v-if="hasPermission(['system:school:list'])" type="success" @click="searchSchool" icon="el-icon-search">查询</el-button>
          </el-form-item>

        <!--  <el-form-item>
            <el-button type="primary" icon="el-icon-location" @click="lookPosition">查看位置</el-button>
          </el-form-item>-->
        </el-form>
        <el-table
          :data="schoolList"
          border
          v-loading="loading"
          style="width: 100%;">

          <el-table-column
            type="selection"
            align="center"
            width="50">
          </el-table-column>

          <el-table-column
            prop="name"
            align="center"
            label="学校名称">
          </el-table-column>

          <el-table-column
            prop="simplicity"
            align="center"
            label="简拼">
          </el-table-column>

          <el-table-column
            prop="principal_name"
            align="center"
            label="校长姓名">
          </el-table-column>

          <el-table-column
            prop="mobile"
            align="center"
            label="联系电话">
          </el-table-column>

          <el-table-column
            prop="create_date"
            align="center"
            width="180"
            :formatter="formatterCreateDate"
            label="创建时间">
          </el-table-column>

          <el-table-column
            prop="update_date"
            align="center"
            width="180"
            :formatter="formatterUpdateDate"
            label="更新时间">
          </el-table-column>

          <el-table-column
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button
                size="small"
                v-if="hasPermission(['system:school:update'])"
                @click="updateSchool(scope.row)"
                type="warning">修改</el-button>
              <el-button
                size="small"
                v-if="hasPermission(['system:school:deleteById'])"
                @click="deleteById(scope.row)"
                type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="sizeChangeHandler"
          @current-change="currentChangeHandler"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-tab-pane>

      <el-tab-pane v-if="hasPermission(['system:school:save', 'system:school:update'])" :label="labelName" name="school_form">
        <el-form :model="form" :rules="rules" style="width: 50%" ref="form" @keyup.enter.native="saveOrUpdate()" label-width="100px">
          <el-form-item label="学校名称" prop="name">
            <el-input v-model="form.name"  @keyup.native="getSpell"  placeholder="请输入学校名称"></el-input>
          </el-form-item>

          <el-form-item label="学校类型" prop="school_type">
            <el-select
              v-model="form.school_type"
              filterable
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in schoolTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="学校简拼" prop="simplicity">
            <el-input v-model="form.simplicity" placeholder="请输入学校简拼"></el-input>
          </el-form-item>

          <el-form-item label="校长姓名" prop="principal_name">
            <el-input v-model="form.principal_name" placeholder="请输入校长姓名"></el-input>
          </el-form-item>

          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入联系电话"></el-input>
          </el-form-item>

          <el-form-item label="联系地址" prop="mobile">
            <el-input v-model="form.address" placeholder="请输入联系地址"></el-input>
          </el-form-item>

          <el-form-item label="学校坐标" prop="position">
            <el-input v-model="form.position" placeholder="学校坐标" @focus="openMap"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="saveOrUpdate" type="primary">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
  import {isMobile} from '@/utils/validate'
  import {getSchoolTypeListApi} from '@/utils/system-dict-api'
  export default {
    name: 'school',
    data () {
      let validatorMobile = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入学校联系方式'))
        } else {
          if (!isMobile(value)) {
            callback(new Error('请输入正确联系方式'))
          }
          callback()
        }
      }

      return {
        labelName: '添加学校',
        loading: false,
        keyWord: '',
        schoolList: [],
        totalCount: 0,
        currentPage: 1,
        pageSize: 10,
        activeName: 'school_list',
        schoolTypeList: [],
        schoolTypeListForQuery: [],
        positionList: [],
       // old_account_number: 0, // 修改之前的学员账号
        form: {
          principal_name: '',
          name: '',
          school_type: '',
          mobile: '',
          simplicity: '',
          address: '',
          position: ''
        },

        query: {
          school_type: '',
          keyWord: ''
        },

        rules: {
          name: [
            {required: true, message: '请输入学校名称', trigger: 'blur'}
          ],
          school_type: [
            {required: true, message: '请选择学校类型', trigger: 'blur'}
          ],
          simplicity: [
            {required: true, message: '请输入学校简称', trigger: 'blur'}
          ],
          principal_name: [
            {required: true, message: '请输入校长姓名', trigger: 'blur'}
          ],
          mobile: [
            {required: true, validator: validatorMobile, trigger: 'blur'}
          ],
          address: [
            {required: true, message: '请输入联系地址', trigger: 'blur'}
          ]
        }
      }
    },

    mounted () {
      if (this.$route.params.activeName) {
        this.activeName = this.$route.params.activeName
      }
      let positionInfo = this.$store.state.map.positionInfo
      console.log(positionInfo.lat)
      if (positionInfo !== undefined) {
        if (positionInfo.lat !== undefined) {
          this.form.lat = positionInfo.lat
          this.form.lng = positionInfo.lng
          this.form.address = positionInfo.address
          this.form.position = this.form.lat + ',' + this.form.lng
        }
      }
      let schoolForm = this.$store.state.map.schoolForm
      if (schoolForm !== undefined) {
        this.form.principal_name = schoolForm.principal_name
        if (schoolForm.id) {
          this.form.id = schoolForm.id
        }
        this.form.name = schoolForm.name
        this.form.mobile = schoolForm.mobile
        this.form.school_type = schoolForm.school_type
        this.form.simplicity = schoolForm.simplicity
      }
      this.getSchoolList()
      let that = this
      getSchoolTypeListApi(data => {
        that.schoolTypeList = data
        that.schoolTypeListForQuery = data
      })
    //  this.getPositionList()
    },

    methods: {
      lookPosition () {
        this.$router.push(
          {
            name: 'baidu-map',
            params: {
              queryAll: true
            }
          }
        )
      },
      formatterCreateDate (row, column) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      formatterUpdateDate (row, column) {
        if (!row.update_date) {
          return '--'
        }
        return this.moment(row.update_date).format('YYYY-MM-DD HH:mm')
      },

      // getPositionList () {
      //   let that = this
      //   that.axios.get(that.$http.httpUrl('/api/pagination')).then(function (response) {
      //     that.$store.commit('map/updatePositionList', response.data)
      //   })
      // },
      searchSchool () {
        this.currentPage = 1
        this.getSchoolList()
      },
      getSchoolType () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            'type': 'school_type'
          }
        }).then(function (response) {
          that.schoolTypeList = response.data.data.dataList
        })
      },

      deleteById (item) {
        let that = this
        item.sqlId = 'system.common.deleteById'
        item.table = 'school_info'
        that.$confirm('确定删除学校[' + item.name + ']？删除后将不可恢复', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/school'), {
            data: item
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getSchoolList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      },
      getSpell () {
        let that = this
        that.axios.get(that.$http.httpUrl('/getSpell'), {
          params: {
            keyWord: that.form.name
          }
        }).then(function (response) {
          that.form.simplicity = response.data
        })
      },
      handleClick (tab) {
        let selectTab = tab.name
        let that = this
        if (selectTab === 'school_list') {
          that.labelName = '添加学校'
        }
        that.clearForm()
      },

      updateSchool (item) {
        this.activeName = 'school_form'
        this.labelName = '修改学校'
        this.form = {
          id: item.id,
          principal_name: item.principal_name,
          name: item.name,
          school_type: item.school_type,
          mobile: item.mobile,
          simplicity: item.simplicity,
          lng: item.lng,
          lat: item.lat,
          address: item.address
        }
        this.form.position = item.lat + ',' + item.lng
      },
      sizeChangeHandler (val) {
        this.pageSize = val
        this.currentPage = 1
        this.getSchoolList()
      },

      currentChangeHandler (val) {
        this.currentPage = val
        this.getSchoolList()
      },

      openMap () {
        this.$store.commit('map/updateSchoolForm', this.form)
        this.$router.push(
          {
            name: 'baidu-map',
            params: {
              queryAll: false, // 是否显示所有学校坐标
              lng: this.form.lng,
              lat: this.form.lat,
              schoolName: this.form.name
            }
          }
         )
      },

      getSchoolList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/school'), {
          params: {
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            keyWord: that.query.keyWord,
            gradeType: that.query.grade_type
          }
        }).then(function (response) {
          that.schoolList = response.data.data.dataList
          that.totalCount = response.data.data.total
        })
      },

      clearForm () {
        this.form = {
          position: '',
          principal_name: '',
          simplicity: '',
          mobile: '',
          alias: '',
          lng: '',
          lat: ''
        }
      },

      saveOrUpdate () {
        let that = this
        that.$refs['form'].validate(function (valid, rules) {
          if (valid) {
            delete (that.form.position)
            that.axios.post(that.$http.httpUrl('/system/school/saveOrUpdate'), that.form)
              .then(function (response) {
                if (response.data.code === 1) {
                  if (!that.form.id) {
                    that.$confirm(response.data.message + ',是否继续添加?', '提示', {
                      confirmButtonText: '继续添加',
                      cancelButtonText: '返回列表',
                      type: 'warning'
                    }).then(() => {
                      that.getSchoolList()
                      that.clearForm()
                    }).catch(() => {
                      that.activeName = 'school_list'
                      that.labelName = '添加学校'
                      that.clearForm()
                      that.getSchoolList()
                    })
                  } else {
                    that.$message({
                      type: 'success',
                      message: response.data.message
                    })
                    setTimeout(function () {
                      that.activeName = 'school_list'
                      that.labelName = '添加学校'
                      that.clearForm()
                      that.getSchoolList()
                    }, 1000)
                  }
                } else {
                  that.$message({
                    type: 'error',
                    message: response.data.message
                  })
                }
              }).catch(function (error) {
                console.log(error)
              })
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      }
    }
  }
</script>

<style>
</style>
